package com.zw.admin.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zw.admin.server.controller.DeviceController;
import com.zw.admin.server.dao.DeviceDao;
import com.zw.admin.server.dto.Device.Iot;
import com.zw.admin.server.model.Device;
import com.zw.admin.server.model.ResponseBean;
import com.zw.admin.server.service.DeviceService;
import com.zw.admin.server.utils.HttpPost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.executable.ValidateOnExecution;
import javax.xml.ws.Response;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceDao deviceDao;

    @Autowired
    private DeviceController deviceController;

    @Value("${baisheng.appId}")
    private String appId;
    @Value("${baisheng.deviceUrl}")
    private String deviceUrl;

    @Override
    public int saveOrUpdate(Device device) {

        //找出Id主键
        Device select = deviceDao.selectByIotId(device.getIotId());
        if (select != null) {
            //如果Id主键不为空，则为更新
            device.setId(select.getId());
            return deviceDao.updateByPrimaryKey(device);
        } else {
            //如果Id主键为空，则为新增
            return deviceDao.insert(device);
        }
    }

    @Override
    public int count(Map<String, Object> params) {
        return deviceDao.count();
    }

    @Override
    public List<Device> list(Map<String, Object> params, Integer offset, Integer limit) {
        if (params.get("name").equals("") && params.get("sn").equals("")) {
            return deviceDao.listAll(params, offset, limit);
        } else if (!params.get("name").equals("") && params.get("sn").equals("")) {
            return deviceDao.listByName(params, offset, limit);
        } else if (params.get("name").equals("") && !params.get("sn").equals("")) {
            return deviceDao.listBySn(params, offset, limit);
        } else {
            return deviceDao.listByAllParam(params, offset, limit);
        }
    }

    @Transactional
    @Override
    public ResponseBean updateDeviceStates(String deviceId, String status) {
        String accessToken = "";
        String typeId = "";
        try {
            accessToken = deviceController.getAccessToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<Object, Object> params = new HashMap<>();
        params.put("appID", Integer.parseInt(appId));

        ArrayList<HashMap<Object, Object>> devices = new ArrayList<>();
        HashMap<Object, Object> devicesMap = new HashMap<>();
        Device device = deviceDao.selectByIotId(deviceId);

        typeId = device.getTypeId();
        devicesMap.put("typeID", typeId);

        HashMap<String, String> statusMap = new HashMap<>();
        //判断开关类型
        if (typeId.equals("07cb95502326de2376339141372ef35c9")) {//单路开关
            statusMap.put("DEV_SWITCH_STA_1", status);
        } else if (typeId.equals("0a0e80c8720c2b3775f1bdf13ca6d4768")) {//双路开关
            statusMap.put("DEV_SWITCH_STA_1", status);
            statusMap.put("DEV_SWITCH_STA_2", status);
        } else {//三路开关
            statusMap.put("DEV_SWITCH_STA_1", status);
            statusMap.put("DEV_SWITCH_STA_2", status);
            statusMap.put("DEV_SWITCH_STA_3", status);
        }

        ArrayList<String> deviceIds = new ArrayList<>();
        deviceIds.add(deviceId);
        devicesMap.put("deviceIDs", deviceIds);
        devicesMap.put("status", statusMap);

        devices.add(devicesMap);

        params.put("devices", devices);

        System.out.println(JSONObject.toJSONString(params));

        String result = "";
        String url = "/api/v1/device/setStatus?access_token=" + accessToken;
        try {
            result = HttpPost.https(deviceUrl + url, params);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String info = JSONObject.parseObject(result).get(typeId).toString();
        String failInfo = "";
        if (!JSONObject.parseObject(info).isEmpty()) {
            failInfo = JSONObject.parseObject(info).get("desc").toString();
        }

        if (failInfo.equals("")) {
            //设备状态设置成功
            return ResponseBean.ok();
        } else {
            //设备状态设置失败
            return ResponseBean.error(500, failInfo);
        }
    }

    public void getOneDayData() {
        deviceDao.getOneDayData();
    }

}
